import datetime

from django.shortcuts import render, reverse
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.contrib.auth.decorators import login_required

from .validations import *


# Create your views here.
def login_view(request):
    template_name = 'users/login.html'
    if request.method == 'GET':
        return render(request, template_name, context=None)
    else:
        username = request.POST.get('username')
        password = request.POST.get('password')
        username_error = valid_login_username(username)
        # 验证用户名是否有误
        if len(username_error) != 0:
            context = {
                'username': username,
                'password': password,
                'username_error': username_error
            }
            return render(request, template_name, context=context)
        password_error = valid_login_password(username=username, password=password)
        # 验证密码是否有误
        if len(password_error) != 0:
            context = {
                'username': username,
                'password': password,
                'password_error': password_error
            }
            return render(request, template_name, context=context)
        # 用户名和密码都正确，让用户登录
        user = auth.authenticate(username=username, password=password)
        auth.login(request, user)
        # 登录之后跳转到首页
        return HttpResponseRedirect(reverse('overview:index'))


def user_view(request):
    template_name = 'users/user.html'
    if request.method == 'GET':
        return render(request, template_name, context=None)
    else:
        return render(request, template_name, context=None)


def register_view(request):
    template_name = 'users/register.html'
    if request.method == 'GET':
        return render(request, template_name, context=None)
    else:
        username = request.POST.get('username')
        password = request.POST.get('password')
        password_confirm = request.POST.get('password_confirm')
        username_error = valid_register_username(username=username)
        password_error = valid_register_password(password=password, password_confirm=password_confirm)
        if len(username_error) == 0 and len(password_error) == 0:
            user = User(username=username)
            user.set_password(password)
            user.save()
            # 注册成功后跳转到登录界面
            return HttpResponseRedirect(reverse('users:login'))
        else:
            context = {
                'username': username,
                'password': password,
                'password_confirm': password_confirm,
                'username_error': username_error,
                'password_error': password_error
            }
            return render(request, template_name, context=context)


@login_required(login_url='users:login')
def logout_view(request):
    auth.logout(request)
    # 注销后跳转到主页
    return HttpResponseRedirect(reverse('overview:index'))


def protocal_view(request):
    return render(request, 'users/protocal.html', context=None)


def retrieve_password_username_view(request):
    template_name = 'users/retrieve/username.html'
    if request.method == 'GET':
        return render(request, template_name, context=None)
    else:
        username = request.POST.get('username')
        username_error = valid_retrieve_username(username=username)
        if len(username_error) == 0:
            user = User.get_user_by_username(username=username)
            return HttpResponseRedirect(reverse("users:retrieve-encrypted", args=(user.id, )))
        else:
            context = {
                'username': username,
                'username_error': username_error
            }
        return render(request, template_name, context=context)


def retrieve_password_security_question_view(request, user_id):
    template_name = 'users/retrieve/security_question.html'
    if request.method == 'GET':
        user = User.get_user_by_id(user_id=user_id)
        context = {
            'user': user
        }
        return render(request, template_name, context=context)
    else:
        answer = request.POST.get('answer')
        user = User.get_user_by_id(user_id=user_id)
        answer_error = valid_retrieve_encrypted(answer=answer, user_answer=user.answer)
        if len(answer_error) == 0:
            return HttpResponseRedirect(reverse("users:retrieve-password", args=(user_id, )))
        else:
            context = {
                'user': user,
                'answer': answer,
                'answer_error': answer_error
            }
            return render(request, template_name, context=context)


def retrieve_password_password_view(request, user_id):
    template_name = 'users/retrieve/password.html'
    if request.method == 'GET':
        user = User.get_user_by_id(user_id=user_id)
        context = {
            'user': user
        }
        return render(request, template_name, context=context)
    else:
        password = request.POST.get('password')
        password_confirm = request.POST.get('password_confirm')
        password_error = valid_retrieve_password(password=password, password_confirm=password_confirm)
        user = User.get_user_by_id(user_id=user_id)
        if len(password_error) == 0:
            user.set_password(password)
            user.save()
            # 密码重置完成回到登录页面
            return HttpResponseRedirect(reverse('users:login'))
        else:
            context = {
                'user': user,
                'password': password,
                'password_confirm': password_confirm,
                'password_error': password_error
            }
        return render(request, template_name, context=context)


@login_required(login_url='users:login')
def user_base_information_view(request, user_id):
    template_name = 'users/settings/base_information.html'
    if request.method == 'GET':
        user = User.get_user_by_id(user_id=user_id)
        context = {
            'user': user
        }
        return render(request, template_name, context=context)
    else:
        sex = request.POST.get('sex')
        school = request.POST.get('school')
        company = request.POST.get('company')
        profession = request.POST.get('profession')
        birthday = request.POST.get('birthday')
        user = User.get_user_by_id(user_id=user_id)
        user.sex = int(sex)
        school_error = valid_school(school=school)
        if len(school_error) == 0:
            user.school = school.strip()
        company_error = valid_company(company=company)
        if len(company_error) == 0:
            user.company = company.strip()
        profession_error = valid_profession(profession=profession)
        if len(profession_error) == 0:
            user.profession = profession.strip()
        # 将接收到的格式为Y-m-d的字符串变成真正意义上的日期
        user.birthday = datetime.datetime.strptime(birthday, '%Y-%m-%d').date()
        user.save()
        context = {
            'user': user,
            'company_error': company_error,
            'school_error': school_error,
            'profession_error': profession_error,
        }
        return render(request, template_name=template_name, context=context)


@login_required(login_url='users:login')
def user_username_view(request, user_id):
    template_name = 'users/settings/username.html'
    if request.method == 'GET':
        user = User.get_user_by_id(user_id=user_id)
        context = {
            'user': user
        }
        return render(request, template_name, context=context)
    else:
        username = request.POST.get('username')
        username_error = valid_register_username(username=username)
        user = User.get_user_by_id(user_id=user_id)
        if len(username_error) == 0:
            user.username = username
            user.save()
        context = {
            'user': user,
            'username': username,
            'username_error': username_error
        }
        return render(request, template_name, context=context)


@login_required(login_url='users:login')
def user_head_portrait_view(request, user_id):
    template_name = 'users/settings/head_portrait.html'
    if request.method == 'GET':
        user = User.get_user_by_id(user_id=user_id)
        context = {
            'user': user
        }
        return render(request, template_name, context=context)
    else:
        image = request.FILES.get('image')
        user = User.get_user_by_id(user_id=user_id)
        # 有上传图片时再修改头像
        if image:
            # 判断图像格式是否正确
            image_error = valid_head_portrait(image)
            if len(image_error) == 0:
                # 首先删除之前保存的文件
                if user.image:
                    user.image.delete()
                # 然后修改保存路径，之后保存图片
                filename = user.username + '_' + image.name
                user.image.save(filename, image)
                context = {
                    'user': user
                }
            else:
                context = {
                    'user': user,
                    'image_error': image_error
                }
            return render(request, template_name, context=context)
        context = {
            'user': user,
        }
        return render(request, template_name, context=context)


@login_required(login_url='users:login')
def user_safety_view(request, user_id):
    """
    账户安全视图，用于邮箱修改和密保设置
    此视图只存在get方法
    :param request:
    :param user_id:
    :return:
    """
    template_name = 'users/settings/safety/safety.html'
    user = User.get_user_by_id(user_id=user_id)
    context = {
        'user': user
    }
    return render(request, template_name, context=context)


@login_required(login_url='users:login')
def user_safety_security_question_view(request, user_id):
    """
    密保问题视图，用于设置密保问题和修改密保问题
    :param request:
    :param user_id:
    :return:
    """
    template_name = 'users/settings/safety/security_question.html'
    if request.method == 'GET':
        user = User.get_user_by_id(user_id=user_id)
        context = {
            'user': user
        }
        return render(request, template_name, context=context)
    else:
        question = request.POST.get('question')
        answer = request.POST.get('answer')
        question_error = valid_question(question=question)
        answer_error = valid_answer(answer=answer)
        user = User.get_user_by_id(user_id=user_id)
        if len(question_error) == 0 and len(answer_error) == 0:
            user.question = question
            user.answer = answer
            user.save()
            context = {
                'user': user
            }
            return HttpResponseRedirect(reverse('users:safety', args=(user.id, )))
        else:
            context = {
                'question_error': question_error,
                'answer_error': answer_error
            }
            return render(request, template_name, context=context)


@login_required(login_url='users:login')
def user_safety_email_view(request, user_id):
    """
    此视图用于对用户邮箱的修改
    :param request:
    :param user_id:
    :return:
    """
    template_name = 'users/settings/safety/email.html'
    if request.method == 'GET':
        user = User.get_user_by_id(user_id=user_id)
        context = {
            'user': user
        }
        return render(request, template_name, context=context)
    else:
        email = request.POST.get('email')
        email_error = valid_email(email=email)
        user = User.get_user_by_id(user_id=user_id)
        if len(email_error) == 0:
            user.email = email
            user.save()
            context = {
                'user': user
            }
            return HttpResponseRedirect(reverse('users:safety', args=(user.id, )))
        else:
            context = {
                'email_error': email_error,
                'user': user
            }
            return render(request, template_name, context=context)


def user_space_view(request, user_id):
    """
    此视图用于显示用户的个人空间，以及展示最近动态
    """
    template_name = 'users/space/index.html'
    if request.method == 'GET':
        user = User.get_user_by_id(user_id=user_id)
        # 获取这位用户的留言和文章
        comments = list(user.platepost_set.filter(status=1))
        department_posts = list(user.departmentpost_set.filter(status=1))
        association_posts = list(user.associationpost_set.filter(status=1))
        # 将留言和文章混合起来，并且进行标记
        for i in range(len(comments)):
            comments[i].class_name = 'PlatePost'
        for i in range(len(department_posts)):
            department_posts[i].class_name = 'DepartmentPost'
        for i in range(len(association_posts)):
            association_posts[i].class_name = 'AssociationPost'
        mixed = comments + department_posts + association_posts
        # 根据created_time进行降序排序
        mixed = sorted(mixed, key=lambda x: x.created_time, reverse=True)
        # 取前１０个，可能不到１０个
        mixed = mixed[:10]
        context = {
            'user': user,
            'mixed': mixed
        }
        return render(request, template_name, context=context)
        

def user_space_post_list_view(request, user_id):
    """
    此视图用于展示该用户写过的文章
    """
    template_name = 'users/space/post_list.html'
    if request.method == 'GET':
        user = User.get_user_by_id(user_id=user_id)
        # 获取社团文章和部门文章
        department_posts = list(user.departmentpost_set.filter(status=1))
        association_posts = list(user.associationpost_set.filter(status=1))
        for i in range(len(department_posts)):
            department_posts[i].class_name = 'DepartmentPost'
        for i in range(len(association_posts)):
            association_posts[i].class_name = 'AssociationPost'
        mixed = department_posts + association_posts
        # 降序排序
        mixed = sorted(mixed, key=lambda x: x.created_time, reverse=True)
        context = {
            'user': user,
            'mixed': mixed
        }
        return render(request, template_name, context=context)


def user_space_comment_list_view(request, user_id):
    """
    此视图用于展示该用户写过的留言
    """
    template_name = 'users/space/comment_list.html'
    if request.method == 'GET':
        user = User.get_user_by_id(user_id=user_id)
        context = {
            'user': user
        }
        return render(request, template_name, context=context)


@login_required(login_url='users:login')
def user_management_view(request, user_id):
    """
    此视图用于用户的一个总的管理界面,用于创建社团，部门
    """
    template_name = 'users/management/index.html'
    if request.method == 'GET':
        user = User.get_user_by_id(user_id=user_id)
        context = {
            'user': user
        }
        return render(request, template_name, context=context)
    

@login_required(login_url='users:login')
def user_management_department_view(request, user_id):
    """
    此视图用于管理自己所创建的部门
    """
    template_name = 'users/management/department.html'
    if request.method == 'GET':
        user = User.get_user_by_id(user_id=user_id)
        context = {
            'user': user
        }
        return render(request, template_name, context=context)
        

@login_required(login_url='users:login')
def user_management_community_view(request, user_id):
    """
    此视图用于管理自己所创建的社团
    """
    template_name = 'users/management/community.html'
    if request.method == 'GET':
        user = User.get_user_by_id(user_id=user_id)
        context = {
            'user': user
        }
        return render(request, template_name, context=context)


@login_required(login_url='users:login')
def user_management_comment_view(request, user_id):
    """
    此视图用于管理自己所创建的留言
    """
    template_name = 'users/management/comment.html'
    if request.method == 'GET':
        user = User.get_user_by_id(user_id=user_id)
        context = {
            'user': user
        }
        return render(request, template_name, context=context)
